import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { login, register, sendVerificationCode } from '@/api/auth'
import Cookies from 'js-cookie'
import { ElMessage } from 'element-plus'

export const useUserStore = defineStore('user', () => {
  const userInfo = ref(null)
  const token = ref(Cookies.get('token') || '')

  // 计算属性：是否已登录
  const isLoggedIn = computed(() => !!token.value)

  // 登录
  const userLogin = async (username, password) => {
    try {
      const data = await login(username, password)
      userInfo.value = data
      token.value = data.token
      
      // 将token存储到cookie中，设置7天过期
      Cookies.set('token', data.token, { 
        expires: 7,
        path: '/',
        secure: false,
        sameSite: 'lax'
      })
      
      // 调试信息：确认token存储
      console.log('Token已存储:', data.token)
      console.log('Cookie中的token:', Cookies.get('token'))
      console.log('Store中的token:', token.value)
      
      ElMessage.success('登录成功')
      return data
    } catch (error) {
      throw error
    }
  }

  // 注册
  const userRegister = async (userData) => {
    try {
      const data = await register(userData)
      ElMessage.success('注册成功，请登录')
      return data
    } catch (error) {
      throw error
    }
  }

  // 发送验证码
  const sendCode = async (mail) => {
    try {
      const data = await sendVerificationCode(mail)
      ElMessage.success('验证码已发送')
      return data
    } catch (error) {
      throw error
    }
  }

  // 登出
  const logout = () => {
    userInfo.value = null
    token.value = ''
    Cookies.remove('token')
    ElMessage.success('已退出登录')
  }

  // 检查认证状态
  const checkAuth = () => {
    const savedToken = Cookies.get('token')
    if (savedToken) {
      token.value = savedToken
      // 这里可以添加验证token有效性的逻辑
    }
  }

  return {
    userInfo,
    token,
    isLoggedIn,
    userLogin,
    userRegister,
    sendCode,
    logout,
    checkAuth
  }
})
